<template>
  <div>
    <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px;">
      <el-form-item label="活动关键字">
        <el-input v-model="searchForm.keyword" placeholder="请输入活动关键字" clearable />
      </el-form-item>
      <el-form-item label="时间区间">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DDTHH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="activities" style="width: 100%">
      <el-table-column prop="title" label="活动名称">
        <template #default="scope">
          <el-link type="primary" @click="goDetail(scope.row)">{{ scope.row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="orgId" label="组织ID" width="100" />
      <el-table-column prop="content" label="活动内容" />
      <el-table-column prop="startTime" label="开始时间" width="170" />
      <el-table-column prop="endTime" label="结束时间" width="170" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const stuId = localStorage.getItem('loginId')
const activities = ref([])
const searchForm = ref({
  keyword: '',
  timeRange: []
})

// 默认加载所有活动并按开始时间倒序排序
const fetchAllActivities = async () => {
  try {
    const res = await axios.get('http://localhost:8080/student/getAllActivity')
    if (res.data && res.data.code === 200) {
      activities.value = (res.data.data || []).sort((a, b) => new Date(b.startTime) - new Date(a.startTime))
      console.log('活动数据:', activities.value)
    } else {
      activities.value = []
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取活动失败')
    }
  } catch (e) {
    ElMessage.error('获取活动失败')
  }
}

onMounted(fetchAllActivities)

// 跳转到活动详情页面
const goDetail = (row) => {
  router.push({ name: 'ActivityDetail', params: { actId: row.actId } })
}

// 搜索功能
const handleSearch = async () => {
  // 按关键字
  if (searchForm.value.keyword) {
    try {
      const res = await axios.get(
        `http://localhost:8080/student/getActivityByKeyword/${searchForm.value.keyword}/${stuId}`
      )
      if (res.data && res.data.code === 200) {
        activities.value = (res.data.data || []).sort((a, b) => new Date(b.startTime) - new Date(a.startTime))
        console.log('按关键字搜索活动:', activities.value)
      } else {
        activities.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '搜索失败')
      }
      return
    } catch (e) {
      ElMessage.error('搜索失败')
      return
    }
  }
  // 按时间区间
  if (searchForm.value.timeRange.length === 2) {
    const [start, end] = searchForm.value.timeRange
    try {
      const res = await axios.get(
        `http://localhost:8080/student/activities/${start}/${end}`
      )
      if (res.data && res.data.code === 200) {
        activities.value = (res.data.data || []).sort((a, b) => new Date(b.startTime) - new Date(a.startTime))
        console.log('按时间区间搜索活动:', activities.value)
      } else {
        activities.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '搜索失败')
      }
      return
    } catch (e) {
      ElMessage.error('搜索失败')
      return
    }
  }
  // 如果都没填，默认显示所有活动
  fetchAllActivities()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.keyword = ''
  searchForm.value.timeRange = []
  fetchAllActivities()
}
</script>